package controller

import (
	"fmt"
	"net/http"

	"own/models"

	"github.com/gin-gonic/gin"
)

func IndexHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", gin.H{"name": "lzmy"})
}

func GetInfoHandler(c *gin.Context) {
	infos, err := models.GetInfo()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"error:": err,
		})
	} else {
		c.JSON(http.StatusOK, infos)
	}
}

func AddInfoHandler(c *gin.Context) {
	var info models.Info
	c.BindJSON(&info)
	err := models.AddInfo(&info)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	} else {
		c.JSON(http.StatusOK, info)
	}
}

func EditInfoHandler(c *gin.Context) {
	var info models.Info
	id, ok := c.Params.Get("id")
	c.BindJSON(&info)
	fmt.Printf("%v\n", info)
	if ok {
		models.EditInfo(id, &info)
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg": "更新失败",
		})
	}
}

func DelInfoHandler(c *gin.Context) {
	fmt.Println("成功")
	id, ok := c.Params.Get("id")
	if ok {
		models.DelInfo(id)
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg": "删除失败",
		})
	}
}
